from flask import Flask,request,session,g,render_template
import config
from exts import db,mail
# from models-back import UserModel,EmailCaptchaModel
from blueprints.qa import bp as qa_bp
from blueprints.auth import bp as auth_bp
from flask_migrate import Migrate

from models.user_model import UserModel
from models.entity_model import EntityModel
from models.email_captcha_model import EmailCaptchaModel
from models.question_model import QuestionModel
from models.Answer_model import AnswerModel

# __name__: 当前 app.py这个模块
app = Flask(__name__)

# 绑定配置文件,自动读取里面的配置信息
# app.config["SQLALCHEMY_DATABASE_URI"] = connection
app.config.from_object(config)

# init_app: SQLAlchemy function: Initialize a Flask application for use with this extension instance
# 取代的是 db = SQLAlchemy(app)
# db.init_app 它的作用是将 SQLAlchemy 实例(db)与 Flask 应用实例(app)进行关联
db.init_app(app)

# mail.init_app: 将 Mail Server与 app 进行关联
mail.init_app(app)

# 使用迁移工具将app和database关联
migrate = Migrate(app, db)

app.register_blueprint(auth_bp)
app.register_blueprint(qa_bp)

# @app.route('/')
# def hello_world():  # put application's code here
#     return render_template("index.html")

# before_request / before_first_request / after_request
@app.before_request
def handle_before_request():
    user_id = session.get('user_id')
    if user_id:
        # 设置全局属性
        user = UserModel.query.get(user_id)
        setattr(g, "user",user)
    else:
        setattr(g,"user",None)

@app.context_processor
def handle_context_processor():
    return {"user": g.user}

if __name__ == '__main__':
    app.run(debug=True)
